package com.example.springboot.mybatis.plus.controller;

import com.example.springboot.mybatis.plus.entity.DemoEntity;
import com.example.springboot.mybatis.plus.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * </p>
 *
 * @author Zero
 * @since 2019/6/14
 */
@RestController
@RequestMapping("/api")
public class DemoController {

    @Autowired
    private DemoService demoService;

    /**
     * 创建一个对象
     * @param entity
     * @return
     */
    @PostMapping("/demos")
    public String save(DemoEntity entity) {
        if (demoService.save(entity)) {
            return "保存成功：" + entity.getId();
        } else {
            return "保存失败！";
        }
    }

    /**
     * 通过id查询一个对象
     * @param id
     * @return
     */
    @GetMapping("/demos/{id}")
    public DemoEntity getOne(@PathVariable(value = "id") String id) {
        DemoEntity entity = demoService.getById(id);
        return entity;
    }

    /**
     * 获取对象列表
     * @return
     */
    @GetMapping("/demos")
    public List<DemoEntity> getAll() {
        List<DemoEntity> list = demoService.list();
        return list;
    }

    /**
     * 通过id更新一个对象
     * @param entity
     * @return
     */
    @PutMapping("/demos")
    public String update(DemoEntity entity) {
        if (demoService.updateById(entity)) {
            return "更新成功：" + entity.getId();
        } else {
            return "更新失败！";
        }
    }

    /**
     * 通过id删除一个对象
     * @param id
     * @return
     */
    @DeleteMapping("/demos/{id}")
    public String delete(@PathVariable(value = "id") String id) {
        if (demoService.removeById(id)) {
            return "删除成功：" + id;
        } else {
            return "删除失败！";
        }
    }

    /**
     * 删除所用用户
     * @return
     */
    @DeleteMapping("/demos")
    public String deleteAll() {
        if (demoService.remove(null)) {
            return "删除成功。";
        } else {
            return "删除失败！";
        }
    }
}
